package com.xdxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdxc.exception.CustomException;
import com.xdxc.mapper.ExamsMapper;
import com.xdxc.model.dto.ExamDto;
import com.xdxc.model.dto.ExamGradeDTO;
import com.xdxc.model.dto.ExamQueryDTO;
import com.xdxc.model.dto.ExamSubmitDto;
import com.xdxc.model.entity.Exams;
import com.xdxc.model.form.ExamsForm;
import com.xdxc.service.ExamsService;
import com.xdxc.utils.DateTimeUtils;
import com.xdxc.utils.SecurityUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.xdxc.utils.DateTimeUtils.DATE_FORMAT;

@Service
public class ExamsServiceImpl extends ServiceImpl<ExamsMapper, Exams> implements ExamsService {

    private final RocketMQTemplate rocketMQTemplate;
    private final ExamsMapper examsMapper;
    public ExamsServiceImpl(RocketMQTemplate rocketMQTemplate,ExamsMapper examsMapper) {
        this.rocketMQTemplate = rocketMQTemplate;
        this.examsMapper = examsMapper;


    }


    @Autowired
    private RedisService redisService;


    @Override
    public Page<Exams> pageExams(ExamQueryDTO queryDTO) {
        return this.lambdaQuery()
                .like(StringUtils.isNotBlank(queryDTO.getTitle()), Exams::getTitle, queryDTO.getTitle())
                .eq(queryDTO.getState() != null, Exams::getState, queryDTO.getState())
                .between(queryDTO.getStartTime() != null && queryDTO.getEndTime() != null,
                        Exams::getCreateTime, queryDTO.getStartTime(), queryDTO.getEndTime())
                .page(new Page<>(queryDTO.getPage(), queryDTO.getSize()));
    }

    /**
     * 获取ss表单数据
     *
     * @param id ssID
     * @return
     */
    @Override
    public ExamsForm getExamsFormData(Long id) {
        Exams entity = this.getById(id);
        return null;
    }

    /**
     * 新增ss
     *
     * @param formData ss表单对象
     * @return
     */
    @Override
    public boolean saveExams(ExamsForm formData) {

        return false;
    }

    /**
     * 更新ss
     *
     * @param id   ssID
     * @param formData ss表单对象
     * @return
     */
    @Override
    public boolean updateExams(Long id,ExamsForm formData) {
        return false;
    }

    /**
     * 删除ss
     *
     * @param ids ssID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteExams(String ids) {
//        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的ss数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();


        return this.removeByIds(idList);
    }
    @Override
    public List<ExamDto> returnExamsData(int page, int size) {

        // 创建分页对象
        Page<Exams> videoPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Exams> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Exams::getOpenType, 5);
        // 使用 MyBatis-Plus 的分页查询
        IPage<Exams> pagedExams = this.page(videoPage, lambdaQueryWrapper);


        List<Exams> examList = pagedExams.getRecords();
        if (examList==null){
            throw new CustomException(0,"错误");
        }
        List<ExamDto>  examDtoList= examList.stream().map(exam -> {
            ExamDto examDto = new ExamDto();
            examDto.setId(exam.getId());
            examDto.setName(exam.getTitle());

            examDto.setDuration(getTime(Long.valueOf(exam.getDuration())));
            examDto.setTotalScore(exam.getTotalScore());
            examDto.setPassScore(exam.getPassScore());
            examDto.setStatus(getStatus(exam.getStartTime(), exam.getEndTime()));

            examDto.setStartTime(DateTimeUtils.formatDateTime(exam.getStartTime(),DATE_FORMAT));
            examDto.setEndTime(DateTimeUtils.formatDateTime(exam.getEndTime(),DATE_FORMAT));

            return examDto;
        }).collect(Collectors.toList());

        return examDtoList;
    }

    @Override
    public Boolean submitExam( ExamSubmitDto examSubmitDto) {

       Boolean bo= redisService.hasKey("exam:"+ SecurityUtils.getCurrentUserId());

       if (!bo){
           throw new CustomException(1500,"非法数据提交，或数据错误");
       }

        examSubmitDto.getId();
        return null;
    }

    @Override
    public IPage<ExamGradeDTO> pageExpiredExams(int page, int pageSize) {
        // 1. 构建分页对象
        Page<Exams> pageInfo = new Page<>(page, pageSize);

        // 2. 构建查询条件：end_time < 当前时间
        LambdaQueryWrapper<Exams> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(Exams::getEndTime, LocalDateTime.now())
                .select(Exams::getId, Exams::getTitle, Exams::getStartTime, Exams::getEndTime)  ;

        Page<Exams> examPage = examsMapper.selectPage(pageInfo, queryWrapper);

        // 2. 转换为 DTO 分页
        return examPage.convert(exam -> {
            ExamGradeDTO dto = new ExamGradeDTO();
            dto.setId(exam.getId());
            dto.setName(exam.getTitle());
            dto.setEndTime(exam.getEndTime());
            dto.setStartTime(exam.getStartTime());
            dto.getGradedCount();
            dto.setStatus("已结束");
            dto.setEndTime(exam.getEndTime());
            return dto;
        });
    }

    @Scheduled(cron = "0 * * * * ?")  // 每分钟执行一次
    public void sendExams() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 构建查询条件：endTime小于当前时间且未发送评分
        QueryWrapper<Exams> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("end_time", now)
                .eq("grading_status", 0); // 假设0表示未发送评分

        // 查询符合条件的考试
        List<Exams> exams = baseMapper.selectList(queryWrapper);

        if (exams != null && !exams.isEmpty()) {
            for (Exams exam : exams) {
                // 发送评分消息到RocketMQ
                rocketMQTemplate.convertAndSend("exam-grading-topic", exam);
                // 更新考试状态为已发送评分
                exam.setGradingStatus(1); // 假设1表示已发送评分
                baseMapper.updateById(exam);
            }
        }
    }
















    public  String getTime(Long minutes) {
        if (minutes < 60) {
            return minutes + "分钟"; // 小于60分钟直接显示分钟
        } else {
            long hours = minutes / 60; // 计算小时
            long remainingMinutes = minutes % 60; // 计算剩余的分钟
            return hours + "小时" + String.format("%02d", remainingMinutes) + "分钟"; // 格式化分钟为两位数
        }
    }
    public int getStatus(LocalDateTime startTime, LocalDateTime endTime) {
        LocalDateTime now = LocalDateTime.now();

        if (now.isBefore(startTime)) {
            return 1; // 当前时间在开始时间之前
        } else if (!now.isAfter(endTime)) {
            return 2; // 当前时间在开始时间和结束时间之间（包括开始和结束时间）
        } else {
            return 3; // 当前时间在结束时间之后
        }
    }
}